var gulp = require('gulp');
var IOReplace = require('gulp-replace');
var FList = require('gulp-filelist');
var less = require('gulp-less');
var connects = require('gulp-connect');
var Frename = require('gulp-rename');
var Finclude = require('gulp-file-include');
var HREplace = require('gulp-html-replace');
var cssMini = require('gulp-clean-css');
var jsMini = require('gulp-uglify');
var jsonFormat = require('gulp-json-format');
var F2json = require('gulp-file-to-json');
var FN2json = require('gulp-filenames-to-json');
var Fcontent2json = require('gulp-file-contents-to-json');
var TOjson = require('gulp-to-json');
var fs = require('fs');

// 批量按模块提取文件列表。
// 需要先定义模块数组；
var MOD = [
    "announce", //0
    "comment",  //1
    "content",  //2
    "formguide",//3
    "link",     //4
    "member",   //5
    "message",  //6
    "mood",     //7
    "pay",      //8
    "poster",   //9
    "search",   //10
    "special",  //11
    "vote",     //12
    "wap"       //13
]
// 循环获取模块文件列表。
gulp.task('getAllFL', function () {
    for (var i in MOD) {
        var SelectMOD = MOD[i]; // NOTE:如果想单独获取只要把MOD[n]，改成对应的值即可，例如:MOD[2]
        gulp.src('lib/default/' + SelectMOD + '/*')
            .pipe(FList(SelectMOD + '.json', { flatten: true }))
            .pipe(gulp.dest('pages'));
    }
});
// 开始按模块模板创建空页面（空HTML）
// NOTE:必须自己做一个空的HTML文件之后再批量生成（不用webpack的话，建议把要引入的css、js文件也写上），
// NOTE: 需先运行task：getAllFL 否则会报找不到文件
// 这一步用的HTML在templates/ByDefault/mod/mod.html
gulp.task('buildPages', ['getAllFL'], function () {
    for (var i in MOD) {
        var SelectMOD = MOD[i]
        var SelectJSONfile = SelectMOD
        var SelectJSON = JSON.parse(fs.readFileSync('pages/' + SelectJSONfile + '.json'));
        for (var t in SelectJSON) {
            gulp.src('templates/ByDefault/mod/mod.html')
                .pipe(HREplace({
                    title: {
                        src: null,
                        tpl: '<title>' + SelectJSON[t] + '</title>'
                    }
                }))
                .pipe(Frename(SelectJSON[t]))
                .pipe(gulp.dest('pages/' + SelectMOD));
        };
    }
});
// PC 标签
// 按模块、模块模板页面归类写成json
// 创建用于最终替换PC标签之后生成最终页面的json文件。
gulp.task('htmlReJSON', function () {
    gulp.src('lib/default/**/*.html')
        .pipe(FList('toBuildTEMP.json', {
            relative: true,
            flatten: false,
            removeExtensions: false
        }))
        .pipe(IOReplace("/", "\":\{\""))
        .pipe(IOReplace(".html\"", "\":{}"))
        .pipe(IOReplace("[", "{"))
        .pipe(IOReplace("]", "}"))
        .pipe(IOReplace('/content/', "contenta"))
        .pipe(IOReplace('\"content\"\:\{', ""))
        .pipe(IOReplace('"video_for_ck":{}','"video_for_ck":{}}'))
        .pipe(gulp.dest('PCtags'));
});